import React, { Component } from 'react'
import {
    Image,
    Spin,
    Switch,
    Table,
    Input,
    Space,
    Popconfirm,
    Button,
    Drawer,
    Modal,
    message,
    Tooltip,
    notification, Form, InputNumber
} from 'antd'
import { requestCategoryList } from '../../../api/category'
import { requestBrandlist } from '../../../api/brand'
import { requestShopList, requestRemoveShopList, updateShopList, requestModifyShopList } from '../../../api/shop'
import { AddShop } from '../AddShop'
import ExportJsonExcel from 'js-export-excel'

import QueueAnim from 'rc-queue-anim'

class ShopModel extends Component {

    isUnload = false

    state = {
        loading: true,
        dataSource: [],
        category: [],
        brand: [],
        proid: '',
        searchValue: '',
        isModalVisible: false,
        editVisible: false,
        editRow: {},
        show: true,
        tableHeight: window.innerHeight - 320
    }

    allData = []

    componentDidMount () {
        this.isUnload = false
        if (!localStorage.getItem('shopNotify')) {
            const key = `open${Date.now()}`
            notification.info({
                message: '使用提示',
                description: '点击表头漏斗图标可以进行筛选，点击表头排序图标可以进行排序',
                duration: null,
                // eslint-disable-next-line
                btn: <a onClick={() => {
                    notification.close(key)
                    localStorage.setItem('shopNotify', true)
                }}>不再提示</a>,
                key
            })
        }

        this.getCategory()
        this.getBanner()
        this.updateData()
    }

    componentWillUnmount () {
        this.isUnload = true
    }

    getCategory () {
        requestCategoryList().then(res => {
            let { category } = this.state
            category = res.data.map(item => {
                return {
                    text: item,
                    value: item
                }
            })
            this.setState({
                category
            })
        })
    }

    getBanner () {
        requestBrandlist().then(res => {
            let { brand } = this.state
            brand = res.data.map(item => {
                return {
                    text: item,
                    value: item
                }
            })
            this.setState({
                brand
            })
        })
    }

    copyWhenClick (text) {
        const copyer = document.getElementById('copy')
        copyer.value = text
        copyer.select()
        document.execCommand('copy')
        message.success('复制商品id成功！')
    }

    updateData () {
        requestShopList().then(res => {
            this.allData = res.data
            if (this.state.searchValue) {
                this.searchData(this.state.searchValue)
            } else {
                this.setState({
                    dataSource: res.data,
                    loading: false
                })
            }
        })
    }

    modifyCheckState (state, proid, type) {
        const { dataSource } = this.state
        const item = dataSource.find(item => item.proid === proid)
        item[type] = !state
        if (type === 'issale' && state) {
            item.isrecommend = false
            item.isseckill = false
        }
        if ((type === 'isrecommend' && !state) || (type === 'isseckill' && !state)) {
            item.issale = true
        }
        if (type === 'isseckill' && !state) {
            if (item.discount > 3) {
                message.warn('折扣没有达到秒杀要求')
                this.setState({
                    _proid: proid,
                    isModalVisible: true
                })
            }else{
                message.success('折扣符合秒杀要求')
            }
        }
        this.setState({
            dataSource
        })
        updateShopList(proid, type, item[type]).then(res => {
            console.log(res)
        })
    }

    searchData (value) {
        const filterData = this.allData.filter(item => item.proname.includes(value) || item.proid === value)
        this.setState({
            dataSource: filterData,
            loading: false
        })
    }

    resetData (e) {
        this.setState({
            searchValue: e.nativeEvent.target.value
        })
        if (!e.nativeEvent.target.value) {
            this.setState({
                dataSource: this.allData
            })
        }
    }

    delete (proid) {
        console.warn(proid)
        requestRemoveShopList(proid).then(res => {
            console.log(res)
            this.updateData()
        })
    }

    edit (proid) {
        let item = this.state.dataSource.find(item => item.proid === proid)
        item = {
            ...item, swiper: item.swiper.map((item, index) => {
                return {
                    thumbUrl: item,
                    name: 'picture' + (index + 1)
                }
            })
        }
        this.setState({
            editRow: item,
            editVisible: true,
            proid
        })
    }

    handerEditVisible () {
        this.setState({
            editVisible: false
        })
    }

    handleOk () {
        this.setState({
            isModalVisible: false
        })
    }

    handleCancel () {
        updateShopList(this.state._proid, 'isseckill', false).then(res => {
            this.modifyCheckState(true, this.state._proid, 'isseckill')
        })
        this.setState({
            isModalVisible: false
        })
    }

    discount (values) {
        requestModifyShopList(this.state._proid, values).then(res => {
            this.updateData()
            this.setState({
                isModalVisible: false
            })
        })
    }

    refresh () {
        this.getCategory()
        this.getBanner()
        this.updateData()
    }

    toExcel () {
        console.log('导出Excel')
        const option = {}
        const date = new Date()

        option.fileName = '产品列表' + date.getTime()

        option.datas = [
            {
                sheetData: this.state.dataSource,
                sheetName: 'sheet',
                sheetFilter: ['proname', 'desc', 'category', 'brand', 'originprice', 'discount', 'stock', 'swiper'],
                // sheetHeader: ['产品名称', '产品介绍', '分类', '品牌', '原价', '折扣', '库存', '商品图片'],
                sheetHeader: ['proname', 'desc', 'category', 'brand', 'originprice', 'discount', 'stock', 'swiper'],
                columnWidths: [20, 20],
            },
        ]

        const toExcel = new ExportJsonExcel(option) //new
        toExcel.saveExcel()
    }

    render () {
        let { loading } = this.state
        let element = null
        const columns = [
            {
                title: '序号',
                key: 'index',
                fixed: 'left',
                width: 80,
                render: (text, record, index) => index + 1,
            },
            {
                title: '商品名称',
                fixed: 'left',
                width: 220,
                dataIndex: 'proname',
                key: 'proname',
                // eslint-disable-next-line
                render: (text, record) => <a onClick={this.copyWhenClick.bind(this, record.proid)}>{text}</a>
            },
            {
                title: <Tooltip title="点击右面漏斗进行筛选">商品分类</Tooltip>,
                width: 120,
                dataIndex: 'category',
                filters: [...this.state.category],
                onFilter: (value, record) => record.category === value,
                key: 'category',
            },
            {
                title: <Tooltip title="点击右面漏斗进行筛选">商品品牌</Tooltip>,
                width: 120,
                dataIndex: 'brand',
                filters: [...this.state.brand],
                onFilter: (value, record) => record.brand === value,
                key: 'brand',
            },
            {
                title: '商品图片',
                width: 120,
                dataIndex: 'swiper',
                key: 'swiper',
                render: (value) => <Image key="img" src={value[0]} width={100} height={100} placeholder={
                    <Image
                        preview={false}
                        src="https://web.chengqige.com/vipshop/v1/dist/static/loading.gif"
                        width={100}
                        height={100}
                    />
                }/>
            },
            {
                title: '商品原价',
                width: 120,
                dataIndex: 'originprice',
                sorter: (a, b) => a.originprice - b.originprice,
                key: 'originprice'
            },
            {
                title: '商品折扣',
                width: 120,
                dataIndex: 'discount',
                sorter: (a, b) => a.discount - b.discount,
                key: 'discount'
            },
            {
                title: '销量',
                width: 120,
                dataIndex: 'sales',
                sorter: (a, b) => a.sales - b.sales,
                key: 'sales'
            },
            {
                title: '秒杀',
                width: 80,
                fixed: 'right',
                dataIndex: 'isseckill',
                key: 'isseckill',
                filters: [{ text: '秒杀产品', value: true }, { text: '非秒杀产品', value: false }],
                onFilter: (value, record) => record.isseckill === value,
                render: (text, record, index) => (<Switch size={'small'} checked={record.isseckill}
                                                          onClick={this.modifyCheckState.bind(this, record.isseckill, record.proid, 'isseckill', index)}/>)
            },
            {
                title: '推荐',
                width: 80,
                fixed: 'right',
                dataIndex: 'isrecommend',
                key: 'isrecommend',
                filters: [{ text: '推荐产品', value: true }, { text: '非推荐产品', value: false }],
                onFilter: (value, record) => record.isrecommend === value,
                render: (text, record, index) => (<Switch size={'small'} checked={record.isrecommend}
                                                          onClick={this.modifyCheckState.bind(this, record.isrecommend, record.proid, 'isrecommend', index)}/>)
            },
            {
                title: '上架',
                width: 80,
                fixed: 'right',
                dataIndex: 'issale',
                key: 'issale',
                filters: [{ text: '上架产品', value: true }, { text: '下架产品', value: false }],
                onFilter: (value, record) => record.issale === value,
                render: (text, record, index) => (<Switch size={'small'} checked={record.issale}
                                                          onClick={this.modifyCheckState.bind(this, record.issale, record.proid, 'issale', index)}/>)
            }, {
                title: '操作',
                key: 'action',
                width: 150,
                fixed: 'right',
                render: (text, record, index) => (
                    <Space size="middle" key="action">
                        <Button size={'small'} onClick={this.edit.bind(this, record.proid)}>
                            编辑
                        </Button>
                        <Popconfirm onConfirm={this.delete.bind(this, record.proid)} title="确认删除商品嘛？">
                            <Button size={'small'} danger>
                                删除
                            </Button>
                        </Popconfirm>
                    </Space>)
            }
        ]
        if (loading) {
            element = <div className="loading">
                <Spin tip="Loading..." spinning={loading} size="large"/>
            </div>
        } else {
            element = <div>
                <Space style={{ width: '100%' }} direction="vertical">
                    <Space style={{ width: '100%' }}>
                        <Input.Search allowClear style={{ width: window.innerWidth * 0.15 }} placeholder="请输入名称或ID"
                                      onSearch={this.searchData.bind(this)}
                                      onChange={this.resetData.bind(this)}/>
                        <Button type="primary" onClick={this.toExcel.bind(this)}>导出Excel</Button>
                    </Space>

                    <Table style={{ width: '100%' }} dataSource={this.state.dataSource} columns={columns}
                           scroll={{ y: this.state.tableHeight }} rowKey={record => record.proid}/>
                </Space>
                <Drawer className="EditModel" visible={this.state.editVisible} width={500} title="编辑商品数据"
                        onClose={this.handerEditVisible.bind(this)} footer={null}>
                    <AddShop cb={this.refresh.bind(this)} edit={true} show={true} initData={this.state.editRow}
                             proid={this.state.proid}/>
                </Drawer>
                <Modal title="秒杀降价处理" visible={this.state.isModalVisible}
                       onOk={this.handleOk.bind(this)}
                       onCancel={this.handleCancel.bind(this)} footer={null}>
                    <Form
                        labelCol={{
                            width: 600
                        }}
                        wrapperCol={{
                            span: 10,
                        }}
                        onFinish={this.discount.bind(this)}
                        initialValues={{discount:3}}
                    >
                        <Form.Item name="discount" label="折扣：1-3折" rules={[
                            {
                                required: true,
                                message: '请输入折扣',
                            },
                        ]}>
                            <InputNumber min={1} max={3}/>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                打折秒杀
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        }

        return (<QueueAnim className="demo-content" key="demo">
            {this.props.show ? <div className="demo-tbody" key="a">{element}</div> : null}
        </QueueAnim>)
    }
}

export default ShopModel
